#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np

import os
import glob
import tool_europa as te
import tool_math as tm
import cPickle as pickle

path_pickle = 'out.pickle'
d = pickle.load(open(path_pickle))
selected_languages = d.keys()

rep = []
rep_couple = []
for lg,info in d.iteritems() :
  total = info['total']
  rep.append(total)
  rep_couple.append((lg, total))

frontiers = tm.frontier_entangled_mean(rep, 3)
parts = {}
start = 0
for f in frontiers :
  parts[(start,f)]=[]
  start = f
maxi = max(rep)
if start < maxi :
  parts[(start,maxi+1)] = []

#em = tm.sublist_between(rep, fr)

for lg, total in rep_couple :
  for (start,end),l in parts.iteritems() :
      if start <= total < end :
          parts[(start,end)].append(lg)


p1 = ['al','ar', 'ga', 'ru', 'no', 'tr', 'be', 'hr', 'fa']
p2 = ['ro', 'bg', 'cs', 'et', 'lv', 'lt', 'hu', 'sk', 'mt', 'sl', 'pl']
p3 = ['pt', 'fi', 'da', 'sw', 'el', 'nl', 'es', 'it']
p4 = ['fr', 'de', 'en']

def cmp_lg(x,y) :
  totalx = d[x]['total']
  totaly = d[y]['total']
  return totalx - totaly

p1.sort(cmp_lg)
p2.sort(cmp_lg)
p3.sort(cmp_lg)
p4.sort(cmp_lg)

def get_list_total(list_lg, info): 
  res = []
  for lg in list_lg :
    total = d[lg]['total']
    res.append(total)
  return res


list_part = [p1,p2,p3,p4]
#list_part = [p1, p2]
list_color = ['r','g','b','y']

fig = plt.figure()
last_len = 0
list_barre = []
ax = fig.add_subplot(111)
wb = 0.1

for i,p in enumerate(list_part) :
  list_barre.append([])
  for j,elt in enumerate(p) :
    list_val = get_list_total([elt],info)
    carac_bar = wb*j + last_len*wb
    barre = ax.bar(carac_bar, list_val, width=0.05, color=list_color[i])
    list_barre[i].append(barre)
  last_len += len(p)

#ax.yaxis = list_val
list_legend = []
list_name_legend = []
list_name_legend_light = []
list_ticks = []
last_tick = 0.
last_mid_tick = 0.
for i,b in enumerate(list_barre) :
  lb = len(b)
  list_legend.append(b[0])
  all_lg = ','.join(list_part[i])
  list_name_legend.append('G%d %s'%(i,all_lg))
  list_name_legend_light.append('G%s'%(i))
  if len(list_ticks) != 0 :
    last_tick = list_ticks[-1]
    last_mid_tick = len(list_barre[i-1]) / 2. * wb
  list_ticks.append(last_tick + last_mid_tick + (lb/2.)*0.1)
  
ax.set_xticks(list_ticks)
ax.set_xticklabels(list(list_name_legend_light))
ax.legend(list_legend, list_name_legend, loc = (0.01, 0.55))
plt.savefig('histogramme_groupe_lg.png')
